import { Inject, Provide } from '@midwayjs/decorator';
import { Repository } from 'typeorm';
import { ICoolCache, Cache } from 'midwayjs-cool-core';

import { BsProvinceEntity } from '../entity/bsProvince';
import { BsCityEntity } from '../entity/bsCity';
import { BsAreaEntity } from '../entity/bsArea';
import { BsStreetEntity } from '../entity/bsStreet';
import { InjectEntityModel } from '@midwayjs/orm';

@Provide()
export class CommAddressService {
  @InjectEntityModel(BsProvinceEntity)
  bsProvinceEntity: Repository<BsProvinceEntity>;

  @InjectEntityModel(BsCityEntity)
  bsCityEntity: Repository<BsCityEntity>;

  @InjectEntityModel(BsAreaEntity)
  bsAreaEntity: Repository<BsAreaEntity>;

  @InjectEntityModel(BsStreetEntity)
  bsStreetEntity: Repository<BsStreetEntity>;

  @Inject('cool:cache')
  coolCache: ICoolCache;

  // 以下是获取省份、城市、区域、街道信息的服务
  @Cache(60)
  async getProvince() {
    return await this.bsProvinceEntity.find({
      select: [
        'PROVINCE_ID',
        'PROVINCE_CODE',
        'PROVINCE_NAME',
        'SHORT_NAME',
        'LNG',
        'LAT',
      ],
      order: { SORT: 'ASC' },
    });
  }

  @Cache(60)
  async getCity(provinceCode: string) {
    return await this.bsCityEntity.find({
      where: { PROVINCE_CODE: provinceCode },
      select: [
        'PROVINCE_CODE',
        'CITY_ID',
        'CITY_CODE',
        'CITY_NAME',
        'SHORT_NAME',
        'LNG',
        'LAT',
      ],
      order: { SORT: 'ASC' },
    });
  }

  @Cache(60)
  async getArea(cityCode: string) {
    return await this.bsAreaEntity.find({
      where: { CITY_CODE: cityCode },
      select: [
        'CITY_CODE',
        'AREA_ID',
        'AREA_CODE',
        'AREA_NAME',
        'SHORT_NAME',
        'LNG',
        'LAT',
      ],
      order: { SORT: 'ASC' },
    });
  }

  @Cache(60)
  async getStreet(areaCode: string) {
    return await this.bsStreetEntity.find({
      where: { AREA_CODE: areaCode },
      select: [
        'AREA_CODE',
        'STREET_ID',
        'STREET_CODE',
        'SHORT_NAME',
        'LNG',
        'LAT',
      ],
      order: { SORT: 'ASC' },
    });
  }
}
